/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jdbcmigration;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author tkm
 */
public class MSSQLJDBC extends JDBCDatabase {

    MSSQLJDBC(String host, String port, String dabase, String user, String pass) {
        //初始化数据
        super(host, port == null ? Constant.MSSQLPort : port, dabase == null ? "" : dabase, user, pass, false, null);
    }

    @Override
    void open() {
        try {
            Class.forName(Constant.MSSQLDriver).newInstance();    // 调用sql server驱动
            String replaceurl = Constant.MSSQLURL.replaceFirst("DATABASE_HOST", h).replaceFirst("DATABASE_PORT", p).replaceFirst("DATABASE_NAME", d);
            connection = DriverManager.getConnection(replaceurl, user, pass);  //建立connection连接
        } catch (Exception e) {
            Validator.isTrue(false, e.getMessage());
        }

    }

    @Override
    void close() {
    }

    @Override
    Table[] getTables(String database) {

        try {
            String sql = "Select NAME FROM  SysObjects Where XType='U' orDER BY Name " + "  ";   //得到所有用户表
            Statement createStatement = connection.createStatement();
            ResultSet table = createStatement.executeQuery(sql);
            ArrayList<String> tablearray = new ArrayList<String>();
            while (table.next()) {
                boolean test = Utils.teststringInArray(table.getString("NAME"), "sysdiagrams");
                if (test) {
                    continue;
                }
                tablearray.add(table.getString("NAME"));
            }

            tables = new Table[tablearray.size()];
//            得到每一个表的每一个字段
            for (int i = 0; i < tables.length; i++) {
                String tablename = tablearray.get(i);
                String lsql = "select  top  1 *   from   " + tablename;
                ResultSet column = createStatement.executeQuery(lsql);
                ResultSetMetaData metaData = column.getMetaData();
                Column[] nColumn = new Column[metaData.getColumnCount()];
                for (int j = 1; j <= metaData.getColumnCount(); j++) {
                    Column corow = new Column();
                    corow.setColumn(metaData.getColumnName(j), metaData.getColumnTypeName(j), metaData.getColumnDisplaySize(j), metaData.getScale(j), false, "", false);
                    nColumn[j - 1] = corow;
                }
                Table te = new Table(database, tablename, nColumn);  //设置表格属性
                tables[i] = te;
            }
        } catch (Exception ex) {
            Validator.isTrue(false, "getTable  error:" + ex.getMessage());
        }
        return tables;
    }

    @Override
    void MigrationTo(JDBCDatabase jDatabase) {
        try {
            Validator.isTrue(jDatabase != this, "Cannot  migration to self!");
             Validator.notNull(d, "Database not be null!");
            state = true;
            open();            //打开数据库
            jDatabase.clearDataBase();
            jDatabase.open();  //迁移对象打开数据库
            jDatabase.newDatabase(d);  //对方数据库新建数据库
            Table[] customTables = getTables(d);  //得到sql server的所有表
            Validator.notNull(customTables, "custom ");  //必须有一个表
            for (int i = 0; i < customTables.length; i++) {
                //遍历每一个表，
                Table table = customTables[i];

                //得到每一个表的内容
                String tablecontent = "select * from  " + table.getTableName();
                Statement datecontent = connection.createStatement();
                ResultSet dataResultSet = datecontent.executeQuery(tablecontent);

                //对方数据库插入表，并插入数据
                jDatabase.insertTableContent(table, dataResultSet);

            }
        } catch (Exception ex) {

            Validator.isTrue(false, "mssql MigrationTo error:" + ex.getMessage());
        }
    }

    @Override
    void newDatabase(String dabase) {
        try {
            dropDatabaseIfExist(dabase);     //在这个之前先去掉以前的数据库

            String createurl = "CREATE DATABASE DATABASE_NAME DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
            createurl = createurl.replaceFirst("DATABASE_NAME", dabase);

            //建数据库
            Statement mysqlstatement = connection.createStatement();
            mysqlstatement.execute(createurl);
        } catch (Exception ex) {
            Validator.isTrue(false, "mysql create error:" + ex.getMessage());
        }
    }

    @Override
    void dropDatabaseIfExist(String dabase) {
       try {
            //删掉数据库
            String dropurl = " DROP DATABASE   DATABASE_NAME";
            dropurl = dropurl.replaceFirst("DATABASE_NAME", dabase);
            Statement mysqlstatement = connection.createStatement();
            mysqlstatement.execute(dropurl);
        } catch (Exception ex) {
        }
    }

    @Override
    void useDatabase(String database) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    void insertTableContent(Table table, ResultSet source) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
